package com.ruoyi.applet.utli;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ruoyi.system.api.domain.User;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {

    private static final String secert_KEY = "779897845";

    private static final Integer EXPIRE_TIME = 60000; // Token有效期(毫秒)

    public static String generateToken(User user) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, EXPIRE_TIME);
        return JWT.create()
                .withClaim("usrId",user.getUsrId())
                .withExpiresAt(instance.getTime()) // 设置过期时间
                .sign(Algorithm.HMAC256(secert_KEY)); // 使用HMAC256算法和密钥签名;
    }


    public static Map<String, Object> parseToken(String token) {
        Map<String, Object> claims = new HashMap<>();
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secert_KEY)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            claims.put("usrId",decodedJWT.getClaim("usrId").asInt());
            claims.put("expiresAt", decodedJWT.getExpiresAt());
        } catch (JWTVerificationException exception) {
            // 处理token验证失败的情况，例如token过期或签名不匹配
            // 这里可以根据实际情况记录日志或抛出自定义异常

        }
        return claims;
    }

    public static boolean verify() {
        try {
            JWT.require(Algorithm.HMAC256(secert_KEY)).build();
        } catch (JWTVerificationException exception) {
            // 处理token验证失败的情况，例如token过期或签名不匹配
            // 这里可以根据实际情况记录日志或抛出自定义异常
            return false;
        }
        return true;
    }
}